package com.rem.concurrency.juc.my6Rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * <p>
 * <p>
 * 独占锁（写锁） 一次只能被一个线程占有
 * 共享锁（读锁） 多个线程可以同时占有
 * ReadWriteLock
 * 读-读 可以共存！
 * 读-写 不能共存！
 * 写-写 不能共存！
 *
 * @author Rem
 * @date 2021-03-09
 */

public class ReadWriteLockDemo {

    public static void main(String[] args) throws InterruptedException {

        MyCacheLock myCacheLock = new MyCacheLock();

        new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                myCacheLock.put(String.valueOf(i), Thread.currentThread().getName() + i);
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                myCacheLock.get(String.valueOf(i));
            }
        }, "B").start();

    }
}

class MyCacheLock {

    private Map<String, Object> map = new HashMap<>();
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入OK");
        } finally {
            lock.writeLock().unlock();
        }
    }

    void get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取ok:" + o);
        } finally {
            lock.readLock().unlock();
        }
    }
}


